package com.hs.hlw.credit.system.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SysUserServiceImpl
 *
 * @author zhb
 * @date 2018/08/23
 */
@Service
public class StringUtil {
    /**
     * 手机号验证
     *
     * @param phone
     * @return 验证通过返回true
     */
    public static boolean isMobile(String phone) {
        if (phone == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[1][3,4,5,7,8,9][0-9]{9}$");
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    /**
     * 通过正则表达式进行比对
     *
     * @param regex
     * @param value
     * @return
     */
    public static boolean matchByRegex(String regex, String value) {
        if (value == null) {
            return false;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }

    /**
     * 通过时间格式进行比对
     *
     * @param dateFormat
     * @param value
     * @return
     */
    public static boolean matchByDateFormat(String dateFormat, String value) {
        if (StringUtils.isBlank(dateFormat) || StringUtils.isBlank(value)) {
            return false;
        }
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        try {
            format.parse(value);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    /**
     * double转字符串，并去掉小数位多余的0
     *
     * @param num
     * @return
     */
    public static String dealDoubleValue(double num) {
        String value = num + "";
        while (value.contains(".") && value.endsWith("0")) {
            value = value.substring(0, value.length() - 1);
        }
        if (value.endsWith(".")) {
            value = value.substring(0, value.length() - 1);
        }
        return value;
    }

    /**
     * IP验证
     *
     * @param ip
     * @return 验证通过返回true
     */
    public static boolean isIpAddress(String ip) {
        if (ip == null) {
            return false;
        }
        Pattern pattern = Pattern.compile("^((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))$");
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();
    }

    public static void main(String[] args) {
        System.out.println(dealDoubleValue(2.00100));
    }
}
